package org.example.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yc.damai.dto.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LogoutFilter extends ZuulFilter {

    @Autowired
    LoginFilter loginFilter;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return loginFilter.shouldFilter("login/logout");
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Cookie cookie = new Cookie("loginToken", "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        context.getResponse().addCookie(cookie);
        context.setSendZuulResponse(false);
        if(request.getHeader("Accept").startsWith("application/json")){
            // ajax 请求
            Result result = new Result(1, "退出成功!", null);
            try {
                String json = new ObjectMapper().writeValueAsString(result);
                context.getResponse().setContentType("application/json;charset=utf-8");
                context.getResponse().getWriter().append(json);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            // 表单 请求
//            context.setResponseStatusCode(301);
            try {
                context.getResponse().sendRedirect("/index.html");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
